package com.lanxum.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

/**
 * @author li.sun
 * @Description: PDF文件合并
 * @date 2020/10/18 23:16
 */
public class FileUtil {


    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    private static File file;

//	public static void main(String[] args) {
//		// 待合并的文件，如果有更多个，则在files数组中添加更多个(使用绝对路径)
//		String[] files = { "C:\\Users\\Yang\\Desktop\\mergetest\\1.pdf", "C:\\Users\\Yang\\Desktop\\mergetest\\2.pdf","C:\\Users\\Yang\\Desktop\\mergetest\\3.pdf" };
//		// 合并后的文件(使用绝对路径)
//		String newfile = "C:\\Users\\Yang\\Desktop\\mergetest\\out.pdf";
//		mergePdfFiles(files, newfile);
//	}

    public static boolean mergePdfFiles(String[] files, String newfile) {
        boolean retValue = false;
        Document document = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                file = new File(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                    page.closePath();
                }
                reader.close();
                if (!StringUtils.equals("BlankPage.pdf", file.getName())) {
                    file.delete();
                }
            }
            copy.close();
            retValue = true;
        } catch (Exception e) {
            logger.error("FileUtil--Exception：{}", e);
        } finally {
            document.close();
        }
        return retValue;
    }

    /**
     * 截取pdfFile的第from页至第end页，组成一个新的文件名
     *
     * @param respdfFile 需要分割的PDF
     * @param savepath   新PDF
     * @param from       起始页
     * @param end        结束页
     */
    public static void splitPDFFile(String respdfFile, String savepath, int from, int end) {
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            reader = new PdfReader(respdfFile);
            int n = reader.getNumberOfPages();
            if (end == 0) {
                end = n;
            }
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(savepath));
            document.open();
            for (int j = from; j <= end; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }

            document.close();

        } catch (Exception e) {
            logger.error("截取PDF异常，Exception：{}", e);
        } finally {
            copy.close();
            reader.close();
        }

    }

}
